package com.donger.sso.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.common.core.utils.BizException;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.sso.system.entity.SysDict;
import com.donger.sso.system.entity.SysDictItem;
import com.donger.sso.system.mapper.SysDictItemMapper;
import com.donger.sso.system.service.SysDictItemService;
import com.donger.sso.system.service.SysDictService;
import com.donger.sso.utils.entity.BaseController;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RequestMapping("/dict")
@RestController
@Slf4j
@AllArgsConstructor
public class SysDictController extends BaseController<SysDictService,SysDict> {
    private final SysDictItemService sysDictItemService;


    @GetMapping("/type/{type}")
    public Result<List<HashMap>> getByType(@PathVariable("type") String type) {

        SysDict one = Optional.ofNullable(baseService.getOne(Wrappers.<SysDict>lambdaQuery().eq(SysDict::getType, type)))
                .orElseThrow(() -> new BizException("字典中不存在该类型数据"));
        List<HashMap> list = sysDictItemService.list(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, one.getId()))
                .stream().map(item -> {
                    HashMap<String, String> hashMap = new HashMap<>(2);
                    hashMap.put("value", item.getItemCode());
                    hashMap.put("label", item.getItemText());
                    return hashMap;
                }).collect(Collectors.toList());

        return Res.ok(list);
    }
}
